from app import db
from mongoengine import Q

class HumidityData(db.Document):
    topic = db.StringField()
    type = db.StringField()
    humidity = db.FloatField()
    ts = db.FloatField()
    status = db.StringField(default='no')
    meta = {'collection': 'HumidityDatas', 'strict': False}

    @classmethod
    def get_all(cls, room):
        count = cls.objects(topic__contains=room, status__not__contains='ok')
        result = cls.objects(topic__contains=room)
        return result, len(count)

    @classmethod
    def get_recent_data(cls, roomId, ts, page=1, size=20):
        result = cls.objects(topic__contains=roomId, ts=ts)
        return result[page*size-size:page*size], len(result)

    @classmethod
    def set_stauts(cls, roomId, ts):
        result = cls.objects(topic__contains=roomId, ts=ts).update(status='ok')
        return

    @classmethod
    def check_status(cls, topic, ts, type):
        result = cls.objects(topic=topic, ts=ts, type=type).first()
        return result

    @classmethod
    def get_all_data(cls, begin, end, page, size):
        result = cls.objects(ts__gte=begin, ts__lte=end)
        return result[page*size-size, page*size], len(result)

    @classmethod
    def get_nok_data(cls, roomId, begin, end, page=1, size=20):
        result = cls.objects(topic__contains=roomId, ts__gte=begin, ts__lte=end, status__not__contains='ok')
        return result[page*size-size, page*size]

    def json(self):
        return {
            "room": self.topic.split('/')[1],
            "humidity": self.humidity,
            "ts": self.ts,
            "status": "nok" if (self.status is None) or (self.status == 'no') else "ok",
            "type": self.type
        }